/**
 * 检测点集中是否存在聚集团，并设置相邻点数量超过3个的点的value为10
 * @param {Array} points - 点坐标数组，格式 [{x: x1, y: y1, id: id1}, {x: x2, y: y2, id: id2}, ...]
 * @param {number} threshold - 判定聚集的间距阈值（默认50）
 * @returns {Array} - 返回所有包含超过3个点的聚集组集合，每个点的value设置为10
 */
function detectClusters(points, threshold = 50) {
    const n = points.length;
    const graph = Array.from({ length: n }, () => []);

    // 构建图
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {
            const dx = points[j].x - points[i].x;
            const dy = points[j].y - points[i].y;
            const distanceSquared = dx * dx + dy * dy;

            if (distanceSquared <= threshold * threshold) {
                graph[i].push(j);
                graph[j].push(i);
            }
        }
    }

    const visited = new Array(n).fill(false);
    const clusters = [];

    // 深度优先搜索（DFS）来检测连通分量
    function dfs(node, cluster) {
        visited[node] = true;
        cluster.push(points[node]);

        for (const neighbor of graph[node]) {
            if (!visited[neighbor]) {
                dfs(neighbor, cluster);
            }
        }
    }
// 在构建图之后打印图
console.log("Graph:", graph);
    for (let i = 0; i < n; i++) {
        if (!visited[i]) {
            const cluster = [];
            dfs(i, cluster);
            console.log("Found cluster:", cluster); // 添加这行
            if (cluster.length >= 3) {
                clusters.push(cluster);
            }
        }
    }
// 最后打印 visited 数组
console.log("Visited:", visited);
    // 设置每个点的value为10
    clusters.forEach(cluster => {
        cluster.forEach(point => {
            point.value = 10;
        });
    });

    return clusters;
}

// 示例用法（基于您提供的坐标）
const inputPoints = [
    { x: 893, y: 113, id: 1, value: 10 },
    { x: 900, y: 91, id: 2, value: 20 },
    { x: 915, y: 130, id: 3, value: 10 },
    { x: 908, y: 252, id: 4, value: 20 },
    { x: 901, y: 269, id: 5, value: 20 },
    { x: 904, y: 285, id: 6, value: 20 },
    { x: 758, y: 296, id: 7, value: 30 },
    { x: 871, y: 349, id: 8, value: 10 },
    { x: 761, y: 366, id: 9, value: 30 }
];

const threshold = 50;
const result = detectClusters(inputPoints, threshold);

console.log("聚集的点组：", result);

 